<?php

namespace app\api\Service;

class SendDyxxService
{
    // 刷新access_token
    private static function refreshAccessToken($appid, $appsecret)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($response, true);
        if (isset($data['access_token'])) {
            return $data['access_token'];
        } else {
            return false;
        }
    }

    // 获取新的access_token
    private static function getAccessTokenFromCache($tokenFile)
    {
        if (file_exists($tokenFile)) {
            $tokenData = include($tokenFile);
            if ($tokenData && is_array($tokenData) && isset($tokenData['access_token']) && isset($tokenData['expires_at'])) {
                return $tokenData;
            }
        }
    }

    // 更新access_token缓存文件
    private static function updateAccessTokenCache($tokenFile, $access_token, $expires_in)
    {
        $expires_at = time() + $expires_in - 60;
        $tokenData = "<?php\nreturn array('access_token' => '$access_token', 'expires_at' => $expires_at);\n";
        file_put_contents($tokenFile, $tokenData);
    }

    // 发送订阅消息
    public static function sendMessageWithAccessToken($appid, $appsecret, $template_id, $openid, $data_template)
    {
        $TOKEN_FILE = 'access_token.php';
        $tokenData = self::getAccessTokenFromCache($TOKEN_FILE);

        if ($tokenData && $tokenData['expires_at'] > time()) {
            $access_token = $tokenData['access_token'];
        } else {
            $access_token = self::refreshAccessToken($appid, $appsecret);
            if ($access_token) {
                self::updateAccessTokenCache($TOKEN_FILE, $access_token, 7200);
            } else {
                echo "Access_Token刷新失败\n";
                return;
            }
        }

        // 发送订阅消息的接口
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=$access_token";

        // 需要发送的消息体
        $message_data = [
            "touser" => $openid,
            "template_id" => $template_id,
            "page" => "pages/read/read?aid=360282",
            "miniprogram_state" => "formal",
            "lang" => "zh_CN",
            "data" => $data_template
        ];

        // 初始化cURL
        $ch = curl_init();

        // 配置cURL
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => json_encode($message_data),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json']
        ]);

        // 执行cURL
        $response = curl_exec($ch);

        // 判断发送结果
        if (curl_errno($ch)) {

            // 失败
            echo '执行失败: ' . curl_error($ch);
        } else {

            // 成功
            echo '执行成功: ' . $response;
        }

        // 关闭cURL
        curl_close($ch);
    }
}